package com.three.controller;

import com.three.mapper.StudentMapper;
import com.three.pojo.Result;
import com.three.pojo.Student;
import com.three.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
@Slf4j
@RestController
@CrossOrigin
public class Login {

    @Autowired
    private StudentMapper userMapper;

    @PostMapping("/login")
    // 如果接收的参数是JSON格式的记得务必加上 @RequestBody，否则收到的数据为 null
    public Result login(@RequestBody Student student) {
        log.info("日志 POST /login 学号:" + student.getId());
        Student result = userMapper.select(student);
        // 登录成功,生成令牌并下发令牌
        if (result != null) {
            HashMap<String, Object> data = new HashMap<>();
            data.put("id", result.getId());
            data.put("name", result.getName());
            String jwt = JwtUtils.generateJwt(data);
            return Result.success("登录成功",jwt);
        }
        return Result.fail("用户名或密码错误");
    }
}
